<template>
  <v-touch v-on:swiperight="onSwipeRight"
           :swipe-options="{direction: 'horizontal'}">
    <div style="height: 100%;overflow: auto"
         class="test">
      <popup :value="true"
             :should-rerender-on-show="true"
             :popup-style="{'z-index':500}"
             :show-mask="false"
             height="100%"
             :hide-on-blur="false">
        <x-header v-bind:left-options="{backText: '', preventGoBack: 'true'}"
                  @on-click-back="$router.go(-1)"
                  style="width: 100%">{{row.PROCESSDEFINITION_NAME}}</x-header>
        <div style="height: calc(100% - 42px);overflow-y: hidden">
          <tab :line-width="3"
               custom-bar-width="18px"
               active-color="#343434"
               default-color="#999999"
               bar-active-color="#4D86FF"
               v-model="tab">
            <tab-item v-for="(item, index) in tab_titles"
                      :key="index"
                      :selected="tab === index"
                      @click="tab = index">{{item}}</tab-item>
          </tab>

          <!-- 详情 -->
          <div v-if="tab == 0"
               class="content-container"
               style="padding-top: 6px;">
            <!-- <div class="detail-title">
            <span class="label-before"></span>
            <span>国际风力合同表单修改</span>
          </div> -->
            <template v-for="(item, index) in list"
                      v-if="!item.prop||(item.prop&&!item.prop.showMode)||(item.prop&&item.prop.showMode == 'show')
              ||(item.prop.showMode == 'showOnTaskNode'&&item.prop.showNodes.includes(row.NODEID))">
              <!-- userchoose -->
              <group label-width="100px"
                     :gutter="-1"
                     :key="index"
                     v-if="item.type == 'userchoose'">
                <person-tree :ref="item.Id"
                             v-model="item.value"
                             :title="item.text"
                             value-align="left"
                             :multiple="item.prop.chooseType == 'multi'"
                             :readonly="!flowConfig[item.Id]||(flowConfig&&flowConfig[item.Id]&&!flowConfig[item.Id].editable)"></person-tree>
              </group>
              <!-- radio -->
              <group label-width="100px"
                     :gutter="-1"
                     :key="index"
                     v-else-if="item.type == 'radio'">
                <!-- <x-switch :value="false" :title="item.text" v-model="item.value" :disabled="!flowConfig[item.Id]||(flowConfig&&flowConfig[item.Id]&&!flowConfig[item.Id].editable)"></x-switch> -->
                <popup-radio v-model="item.value"
                             :title="item.text"
                             :placeholder="map[item.type].ph"
                             value-align="right"
                             :options="radio(item.prop.items)"
                             :readonly="!flowConfig[item.Id]||(flowConfig&&flowConfig[item.Id]&&!flowConfig[item.Id].editable)"
                             @on-hide="closeMask"></popup-radio>
              </group>
              <!-- select -->
              <group label-width="100px"
                     :gutter="-1"
                     :key="index"
                     v-else-if="item.type == 'select'">
                <popup-picker v-model="item.value"
                              :title="item.text"
                              :data="analyze(item.prop.items)"
                              :readonly="!flowConfig[item.Id]||(flowConfig&&flowConfig[item.Id]&&!flowConfig[item.Id].editable)"
                              @on-hide="closeMask"></popup-picker>
              </group>
              <!-- input/textarea -->
              <group label-width="100px"
                     :gutter="-1"
                     :key="index"
                     v-else-if="item.type!='attachment' && item.type!='detailtable'"
                     class="detail">
                <!-- v-if不可编辑 -->
                <cell :title="item.text"
                      value-align="right"
                      v-if="!flowConfig[item.Id]||(flowConfig&&flowConfig[item.Id]&&!flowConfig[item.Id].editable)">
                  <div class="black">{{item.value}}</div>
                </cell>
                <!-- 可编辑 -->
                <component :is="map[item.type].comp"
                           :placeholder="map[item.type].ph"
                           columns="1"
                           :title="item.text"
                           v-model="item.value"
                           :rows="1"
                           autosize
                           v-else></component>
              </group>
              <!-- attachment/detailtable -->
              <!-- 对明细表增加监听，监听明细表数据改动-->
              <group v-else
                      class="look"
                     label-width="100px"
                     :key="index"
                     :title="item.text">
                <picture-upload class="file_upload"
                                v-if="item.type == 'attachment'"
                                v-model="item.value"
                                :pageToken="pageToken"
                                :fieldToken="fieldToken"
                                :readonly="!flowConfig[item.Id]||(flowConfig&&flowConfig[item.Id]&&!flowConfig[item.Id].editable)"></picture-upload>
                <detail-table v-if="item.type == 'detailtable'"
                              :prop="item.prop"
                              :value="item.value"
                              @detailChange='changeDetails'
                              :pageToken='pageToken'></detail-table>
              </group>

              <!--<group v-if="index == 0"  style="display:none;">-->
              <!--<cell-->
              <!--is-link-->
              <!--:border-intent="false"-->
              <!--:arrow-direction="showContent ? 'down' : 'right'"-->
              <!--@click.native="showContent = !showContent">-->
              <!--<span slot="title" class="detail-table">明细表</span>-->
              <!--</cell>-->
              <!--</group>-->
              <!--<group v-if="index == 1" title="附件" style="display:none;">-->
              <!--<cell>-->
              <!--<img src="../../assets/img/层级.png" alt="" slot="title">-->
              <!--<span class="attechment-item-name" slot="title">主要内容附件.word</span>-->
              <!--<span class="attechment-item-size">400KB</span>-->
              <!--</cell>-->
              <!--</group>-->
            </template>
          </div>
          <!-- 流程 -->
          <div v-if="tab == 1"
               class="content-container">
            <timeline timeline-theme="#E8EAEB">
              <template v-for="(item, index) in flowList">
                <timeline-item :hollow="true"
                               :key="index"
                               :lineColor="circleColorChange(item.commandMessage)">
                  <div class="flow-box">
                    <div class="flow-box-time">
                      <div>{{item.endTime.split(" ")[0]}} {{item.endTime.split(" ")[1]}}</div>
                      <!-- <div>{{item.endTime.split(" ")[1]}}</div> -->
                    </div>
                    <div class="flow-box-title">{{item.nodeName}}</div>
                    <div class="flow-box-state"
                         :class="styleChange(item.commandMessage)">{{item.commandMessage?item.commandMessage:'待办'}}</div>
                    <div class="flow-box-line"></div>
                    <div class="flow-box-content">
                      <div class="flow-box-point"></div>
                      <span>处理人</span>&nbsp;&nbsp;
                      <div class="name handle">{{item.assignessName}}</div>
                    </div>
                    <div class="flow-box-content"
                         style="margin-top: 10px">
                      <div class="flow-box-point"></div>
                      <span>审批意见</span>&nbsp;&nbsp;
                      <!-- v-html="item.taskComment" -->
                      <!-- <span v-html="item.taskComment"
                            class="handle"></span> -->
                    </div>
                    <div class="flow-box-taskComment">
                      {{item.taskComment}}
                    </div>
                  </div>
                </timeline-item>
              </template>
            </timeline>
          </div>
          <!-- 审批 -->
          <div v-if="tab == 2"
               class="content-container"
               style="margin-top:10px">
            <div>
              <!-- <div class="approve-title"><span class="label-before"></span>审批意见</div> -->
              <group label-width="100px"
                     gutter="-1px"
                     class="approve-textarea">
                <x-textarea placeholder="请输入审批意见"
                            :rows="6"
                            autosize
                            v-model="advice"></x-textarea>
              </group>
            </div>
            <div class="btn-area approve-btn-area">
              <div class="btn"
                  :disable="isDisable"
                   v-for="(item,index) in buttonList"
                   :key="index"
                   v-if="item.commandType&&item.commandType!='saveTaskDraft'&&item.commandType!='processStatus'"
                   @click="confirmDlg(item)">
                <div :class="(item.commandType=='general'?'general-btn':'back-btn')">{{item.text}}</div>
              </div>
            </div>
          </div>
          <!-- 委托 -->
          <div v-if="tab == 3"
               class="content-container"
               style="padding-top: 6px">
            <group label-width="100px"
                   :gutter="0">
              <cell title="当前环节"
                    value-align="right">
                <div class="black">{{checkName(row.NODENAME)}}</div>
              </cell>
              <cell title="原执行人"
                    value-align="right">
                <div class="black">{{user.userName}}</div>
              </cell>
              <person-tree 
                           class="new-name"
                           v-model="newName"
                           title="新执行人"
                           ref="executeLeader"
                           :multiple="false"></person-tree>
              <div class="approve-title"><span class="label-before"></span>委托原因</div>
              <!-- <cell title="委托原因"
                    value-align="right"></cell> -->
              <x-textarea class="approve-textarea-entrust"
                          v-model="reason"
                          placeholder="请输入委托原因"
                          :rows="6"
                          autosize></x-textarea>
            </group>
            <div class="btn-area-entrust"
                 @click="entrust">
              <div class="entrust-btn">确认委托</div>
            </div>
          </div>
        </div>
      </popup>
    </div>
  </v-touch>
</template>

<script>
import {
  Timeline,
  TimelineItem,
  TimelineTitle
} from 'vue-cute-timeline'
export default {
  name: "taskInfo",
  mounted () {
    this.getData();
    this.pageToken = this.guid();
    this.fieldToken = this.guid();
  },
  data () {
    return {
      detailValue: '',
      tab: 0,
      tab_titles: ['详情', '流转', '审批', '委托'],
      formData: [],//原始的业务数据
      buttonList: [],//审批按钮
      flowList: [],//流程列表
      list: [],//业务数据
      advice: '',//审批意见
      newName: '',//委托人
      reason: '',//委托原因
      pageToken: "",
      fieldToken: "",
      isDisable:false,
      showContent: false,
      accordionList: [{ 'name': 'a' }, { 'name': 'b' }, { 'name': 'c' }],
      map: {
        'input': {
          comp: 'x-input',
          ph: '请输入'
        },
        'datetime': {
          comp: 'datetime',
          ph: '请选择'
        },
        'select': {
          comp: 'popup-picker',
          ph: '请选择'
        },
        'userchoose': {
          comp: 'person-tree',
          ph: '请选择'
        },
        'detailtable': {
          comp: 'detail-table'
        },
        'text': {
          comp: 'x-textarea',
          ph: '请输入'
        },
        'attachment': {
          comp: 'photo-upload'
        },
        'radio': {
          comp: 'popup-radio',
          ph: '请选择'
        }
      },//对应组件
    }
  },
  methods: {
    //右滑返回上一层
    onSwipeRight () {
      this.$router.go(-1)
    },
    getData () {
      let configs = JSON.parse(this.row.DATACONFIGS);
      let params = this.getTaskParams(this.row) || '';
      //获取业务数据（主表、明细表（如果有））及任务处理的按钮信息
      this.$ajax({
        method: 'post',
        url: this.COMMON_URL,
        data: {
          FixJSON: params
        }
      }).then((res) => {
        //业务数据
        if (res.data.getData) { 
          this.formData = res.data.getData;
          let value = res.data.getData[configs.bizObjId][0];
          this.list = configs.items.map(item => {
            item.value = value[item.Id] && value[item.Id].val ? (value[item.Id].dis || value[item.Id].val) :
              item.type == "select" ? [] : "";
            //TODO 附件
            // if(item.type == "attachment") {
            //   debugger
            // }
            //TODO end
            if (item.type == 'datetime') {
              item.value = this.formatDateTime(item.value, item.prop)
            } if (item.type == "detailtable") {
              item.value = res.data.getData[item.Id]
            }
            return item
          })
          // this.$store.commit('updateLoadingStatus', false);
          this.getApprovalList();
        }
        //操作按钮
        if (res.data.getToolbar) {
          this.buttonList = res.data.getToolbar[0]
        }
        //将同意 退回按钮调换位置
        var temp = this.buttonList[0];
        this.buttonList[0] = this.buttonList[1];
        this.buttonList[1] = temp;
       
        
      }).catch((err) => {
      });
      console.log(this.list)
    },
    //获取流程意见
    getApprovalList () {//TODO 待完成
      let configs = JSON.parse(this.row.DATACONFIGS);
      // let sys = configs.belongSys.toUpperCase() + '_URL'
      let instId = this.row.INSTID;
      let vText = '{"_method":"flow.getTaskProcess","_param":["' + instId + '"]}';

      this.$ajax({
        method: 'post',
        url: this.COMMON_URL,
        data: {
          FixJSON: vText
        }
      }).then((res) => {
        this.flowList = [];
        if (res.data && res.data.taskListEnd) {
          res.data.taskListEnd.forEach(element => {
            let item = element;
            item.done = true;
            this.flowList.push(item);
          });
        }
        if (res.data && res.data.taskListIng) {
          res.data.taskListIng.forEach(element => {
            let item = element;
            item.done = false;
            this.flowList.push(item)
          });
        }
        this.flowList.splice(0, 1);
      })
    },
    confirmDlg (obj) {

      console.log(this.row)
      let txt = obj.text == "拒绝" ? "退回" : obj.text;
      const _this = this // 需要注意 onCancel 和 onConfirm 的 this 指向
      let content = "是否要执行“" + txt + "”操作？"
      //如果是整改通知单，提交前执行校验方法
      if (this.row.BIZOBJID == 'PMQUALITY_RECTIFY' || this.row.BIZOBJID === 'PMHSE_RECTIFY') {
        let result = this.rectifyCheck(this.row.BIZOBJID)
        content = result.length === 0 ? content : result
      }
      this.$vux.confirm.show({
        // 组件除show外的属性
        title: "提示",
        content: content,
        onCancel () {
        },
        onConfirm () {
          this.isDisable=true;
          _this.flowHandle(obj);
        }
      })
    },
    //流程的提交
    flowHandle (obj) {
      let taskInfor = this.row;
      let configs = JSON.parse(taskInfor.DATACONFIGS);

      let workItemId = taskInfor.TASKID;
      let keyid = taskInfor.BIZKEY;
      let defKey = taskInfor.DEFKEY;
      let FlowID = taskInfor.INSTID;
      let nodeId = taskInfor.NODEID;
      let defId = taskInfor.DEFID;

      let formId = configs.formId; //表单id
      let bizObjId = configs.bizObjId; //业务对象
      let formId_Detail = configs.detailObjIds; //明细表业务对象

      let saveXmlData = this.setModifyData(); //需保存的数据

      //TODO begin 起步没有
      let postFormInfo = {
        "GUID": keyid
      };
      try {
        let tmpData = JSON.parse(saveXmlData);
        for (let i = 0; i < tmpData.length; i++) {
          postFormInfo[tmpData[i].DataTarget] = tmpData[i].Value;
        }
      } catch (e) { } finally {
        postFormInfo = JSON.stringify(postFormInfo);
      }
      //TODO end 起步没有
      if (saveXmlData == "") {
        saveXmlData = "";
      } else {
        let ipos = saveXmlData.length;
        saveXmlData = saveXmlData.substring(1, ipos - 1);
        saveXmlData = ' ,' + saveXmlData;
      }

      let HandleCommand = obj.commandId;
      let userCommandType = obj.commandType;

      let ispass = this.checkForm(userCommandType); //用户自定义校验
      if (!ispass) {
        return false;
      }

      let Advice = this.advice;//审批意见
      if (Advice == "") {
        Advice = obj.text;
      }

      let vText = "";
      if (userCommandType == "_save") {
        vText = '{' +
          '"_method": "formService.saveFormData",' +
          '"requestEventData": {' +
          '"eventType": "formSubmitEvent",' +
          '"formType": 1,' +
          '"bizObjId": "' + bizObjId + '",' +
          '"formId": "' + formId + '",' +
          '"buttonId": "' + HandleCommand + '"' +
          '},' +
          '"_OBJ_NAME_": "' + bizObjId + '",' +
          '"_FORM_ID_": "' + formId + '",' +
          '"useType": "modify",' +
          '"pageToken": "' + this.pageToken + '",' +
          '"formData": {' +
          ' "objName": "' + bizObjId + '",' +
          '"pks": [' +
          '    "GUID"' +
          '],' +
          '"data": [' +
          '    {' +
          '        "rowData": [' +
          '           {' +
          '               "DataTarget": "GUID",' +
          '               "Value": "' + keyid + '",' +
          '               "OriginalValue": "' + keyid + '",' +
          '               "PK": true,' +
          '               "DataType": "String"' +
          '           }' +
          saveXmlData +
          '       ],' +
          '       "children": [' + this.detailValue + ']' +
          '   }' +
          ']' +
          '},' +
          '"_ATTACHMENT_DELETE_IDS_": "",' +
          '"formInfo": ' + postFormInfo +
          '}';
      } else {
        vText = '{' +
          '"_method": "formService.saveFormData",' +
          '"requestEventData": {' +
          '"eventType": "formSubmitEvent",' +
          '"formType": 1,' +
          '"bizObjId": "' + bizObjId + '",' +
          '"formId": "' + formId + '",' +
          '"buttonId": "' + HandleCommand + '"' //??存疑，需要确认
          +
          '},' +
          '"flowParam": {' +
          '"defId": "' + encodeURIComponent(keyid) + '",' +
          '"defKey": "' + defKey + '",' +
          '"instId": "' + FlowID + '",' +
          '"nodeId": "' + nodeId + '",' +
          '"agent": "",' +
          '"userCommandType": "' + userCommandType + '",' +
          '"userCommandId": "' + HandleCommand + '",' //??存疑，需要确认
          +
          '"isAdmin": "false",' +
          '"taskComment": "' + Advice + '",' +
          '"extParam": {  ' +
          '},' +
          '"taskId": "' + workItemId + '"' +
          '},' +
          '"_OBJ_NAME_": "' + bizObjId + '",' +
          '"_FORM_ID_": "' + formId + '",' +
          '"useType": "modify",' +
          '"pageToken": "' + this.pageToken + '",' +
          '"formData": {' +
          ' "objName": "' + bizObjId + '",' +
          '"pks": [' +
          '    "GUID"' +
          '],' +
          '"data": [' +
          '    {' +
          '        "rowData": [' +
          '           {' +
          '               "DataTarget": "GUID",' +
          '               "Value": "' + keyid + '",' +
          '               "OriginalValue": "' + keyid + '",' +
          '               "PK": true,' +
          '               "DataType": "String"' +
          '           }' +
          saveXmlData +
          '       ],' +
          '       "children": [' + this.detailValue + ']' +
          '   }' +
          ']' +
          '},' +
          '"_ATTACHMENT_DELETE_IDS_": "",' +
          '"formInfo": ' + postFormInfo +
          '}';
      }
      this.$ajax({
        method: 'post',
        url: this.COMMON_URL,
        data: {
          FixJSON: vText
        }
      }).then((res) => {
       
        this.$vux.loading.show({
          text: '正在提交'
        })
        if (this.isEmptyObject(res.data)) {
          this.$vux.toast.text('提交成功', 'middle');
          setTimeout(() => {
            this.$vux.toast.hide();
            this.$router.push('/task?refresh=true');
          }, 1000)
        }
         this.$vux.loading.hide()
      })
    },
    //设置要提交的数据
    setModifyData () {
      function getCtlVal (id) {
        return this.dataMap[id].value
      }
      let formData = this.formData
      let taskInfor = this.row;
      let configs = JSON.parse(taskInfor.DATACONFIGS);
      let nodeId = taskInfor.NODEID; //流程当前步奏
      let flowConfig = configs.flowConfig;
      let str = "";
      if (this.isEmptyObject(flowConfig)) {
        return "";
      }
      if (typeof (flowConfig[nodeId]) != "undefined") {
        let saveData = [];
        for (let i = 0; i < flowConfig[nodeId].items.length; i++) {
          let data = {};
          let item = flowConfig[nodeId].items[i];
          let obj = this.dataMap[item.Id];
          if (item.submit) {
            data.DataTarget = item.Id;
            data.OriginalValue = "";
            data.PK = false;
            data.DataType = "String";
            let val = "";
            val = obj.value;
            data.Value = val;
            saveData.push(data);
            if (obj.type == "userchoose") {
              data = {};
              //如果关联的UserName不为空，需要提交这部分的数据
              if (typeof (obj.prop.UserNameRelateId) != "undefined") {
                if (obj.prop.UserNameRelateId != "") {
                  data.DataTarget = obj.prop.UserNameRelateId;
                  data.OriginalValue = "";
                  data.PK = false;
                  data.DataType = "String";
                  let val = "";
                  val = this.getUserVal(item.Id, "username");
                  data.Value = val;
                  saveData.push(data);
                }
              }
              //如果关联的UserNo不为空，需要提交这部分的数据
              if (typeof (obj.prop.UserNoRelateId) != "undefined") {
                if (obj.prop.UserNoRelateId != "") {
                  data.DataTarget = obj.prop.UserNoRelateId;
                  data.OriginalValue = "";
                  data.PK = false;
                  data.DataType = "String";
                  let val = "";
                  val = this.getUserVal(item.Id, "userno");
                  data.Value = val;
                  saveData.push(data);
                }
              }
            }
          }
        }
        //执行自定义代码            
        if (typeof (configs.setModifyData) != "undefined" && configs.setModifyData != "") {
          eval(unescape(configs.setModifyData));
        }
        if (saveData.length > 0)
          str = JSON.stringify(saveData);
      }
      return str;
    },
    //设置表单的校验        
    checkForm (commandType) {
      var self = this;
      function getCtlVal (id) {
        return self.dataMap[id].value;
      }
      let taskInfor = this.row;
      let configs = JSON.parse(taskInfor.DATACONFIGS);
      let nodeId = taskInfor.NODEID;//流程当前步奏
      let flowConfig = configs.flowConfig;
      let formData = this.formData;
      let msg = "";
      if (this.isEmptyObject(flowConfig)) {
        return true;
      }
      if (typeof (flowConfig[nodeId]) != "undefined") {
        for (let i = 0; i < flowConfig[nodeId].items.length; i++) {
          let validateItem = flowConfig[nodeId].items[i];
          if (validateItem.validate) {
            let val = getCtlVal(validateItem.Id);
            if (val == "" && validateItem.commandType.indexOf(commandType) != -1) {
              msg = validateItem.errMsg;
              break;
            }
          }
        }
      }
      //执行自定义代码            
      if (typeof (configs.checkForm) != "undefined" && configs.checkForm != "") {
        eval(unescape(configs.checkForm))
      }
      if (msg == "")
        return true;
      else {
        this.$vux.toast.text(msg, 'middle')
        return false;
      }
    },
    entrust () {
      // 选人过来的员工号（也是“新执行人：的员工号）
      let userID = this.$refs.executeLeader.getValues('USER_NAME');
      // 原执行人的员工号也是登陆人的员工号
      let user = this.user.USER_NO;
      if (userID == "") {
        // 显示文字
        this.$vux.toast.text('请选择新执行人', 'middle')
        return false;
      }
      if (user == userID) {
        this.$vux.toast.text('不能委托给自己！', 'middle')
        return;
      }

      if (!this.reason) {
        this.$vux.toast.text('请输入委托原因', 'middle')
        return false;
      }
      this.doTrust();
    },
    //委托
    doTrust () {      debugger
      let taskInfor = this.row;
      let configs = JSON.parse(taskInfor.DATACONFIGS);

      let consignMemo = this.reason; // 输入的委托原因
      let workItemId = taskInfor.TASKID;
      let keyid = taskInfor.BIZKEY;
      let defKey = taskInfor.DEFKEY;
      let flowID = taskInfor.INSTID;
      let nodeId = taskInfor.NODEID;
      let defId = taskInfor.DEFID;
      let taskExecutorName = this.user.userName; //原执行人姓名
      let taskExecutor = taskInfor.ASSIGNEE; // 登录者的英文名
      let description = taskInfor.DESCRIPTION;
      // let sys = configs.belongSys.toUpperCase() + '_URL'
      //委托人
      let AuditUserFullName2 = "";
      let AuditUserName2 = "";

      AuditUserFullName2 = this.$refs.executeLeader.getValues('USER_FULLNAME')
      AuditUserName2 = this.$refs.executeLeader.getValues('USER_NAME')

      let vText = '{' +
        '"_method":"formflow.doConsignFlow",' +
        '"_param":{' +
        '"flowParam":{' +
        '"defKey":"' + defKey + '",' +
        '"taskId":"' + workItemId + '",' +
        '"instId":"' + flowID + '",' +
        '"userCommandId":"transfer",' // 默认的
        +
        '"userCommandType":"transfer",' // 默认的
        +
        '"isAdmin":true,' // 默认的
        +
        '"taskComment":"委托原因：' + consignMemo + '<br/>原执行人：' + taskExecutorName + '",' // 委托原因+原执行人姓名
        +
        '"businessKey":"' + keyid + '",' +
        '"userName":"' + AuditUserName2 + '",' // 新执行人
        + '"originUserName":"' + taskExecutor + '",'//原执行人
        + '"originUserFullName":"' + taskExecutorName + '",'//原执行人姓名
        +
        '"description":"' + description + '",' + //表单名称
        '"extParam":{' +
        '"transferUserId":"' + AuditUserName2 + '"' // 选人的id
        +
        '}' +
        '}' +
        '}' +
        '}';
      // this.$vux.loading.show({
      //   text: '正在提交'
      // })
      this.$ajax({
        method: 'post',
        url: this.COMMON_URL,
        data: {
          FixJSON: vText
        }
      }).then((res) => {        debugger
        // this.$vux.loading.hide()
        if (this.isEmptyObject(res.data)) {
          this.$vux.toast.text('提交成功', 'middle')
          setTimeout(() => {
            this.$vux.toast.hide()
            this.$router.push('/task?refresh=true')
          }, 1000)
        }
      })

      // appcan.request.ajax({
      //   url: url,
      //   type: 'GET',
      //   data: {
      //     url: vURL,
      //     text: vText
      //   },
      //   dataType: "text",
      //   success: function (data1) {
      //     appcan.window.closeToast();
      //     let vjson = JSON.parse(data1);
      //     if (vjson.status == 0) {
      //       appcan.window.openToast('提交成功', 2000);
      //       appcan.window.evaluatePopoverScript('taskList', 'content', 'getdata(1)');
      //       appcan.window.evaluateScript('index', 'getTaskCount(1);');
      //       appcan.window.evaluateScript("TM-Task", "appcan.window.close(-1)");
      //     } else {
      //       appcan.window.openToast('提交失败', 2000);
      //     }
      //   }
      // });
    },
    checkName (val) {
      if (val) {
        return val.replace(/<[^>]+>/g, '')
      }
    },
    formatDateTime (val, prop) {
      let datetime = new Date(val.replace(new RegExp('-', 'g'), '/'));
      return datetime.pattern(prop.format);
    },
    radio (data) {
      if (!data)
        return false
      let list = []
      list = data.map(item => {
        if (item.value)
          return {
            key: item.value.replace(/(^\s*)|(\s*$)/g, ""),
            value: item.text.replace(/(^\s*)|(\s*$)/g, "")
          }
      })
      return list
    },
    goBack () {
      this.$router.go(-1);
    },
    styleChange (obj) {
      switch (obj) {
        case '提交':
          return 'progress-submit';
          break;
        case '同意':
          return 'progress-agree';
          break;
        case '退回':
          return 'progress-back';
          break;
        case '结束':
          return 'progress-finish';
          break;
        default:
          return 'progress-wait';
          break;
      }
    },
    circleColorChange (obj) {
      switch (obj) {
        case '提交':
          return '#FFCC00';
          break;
        case '同意':
          return '#4CD964';
          break;
        case '退回':
          return '#FF3B30';
          break;
        case '结束':
          return '#D1D1D6';
          break;
        default:
          return '#5AC8FA';
          break;
      }
    },
    /**
     * 将明细表中的值进行修改，并同时生成明细表相应保存字符串。通过明细表相关数据，计算已整改数量和闭合率
     * param:{obj}明细表中的数据对象
     * TODO 该方法目前仅对前海质量和安全模块的整改通知单有效，后续需要调整逻辑将其变成通用方法
     */
    changeDetails (newValue) {
      debugger
      let rectifySum = 0
      let closeRate = 0
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].type === 'detailtable') {
          this.list[i].value = newValue
          let obj = {
            objName: this.list[i].Id,
            pks: ["GUID"],
          }
          let dataList = []
          for (let i = 0; i < newValue.length; i++) {
            let data = {}
            let rowData = []
            for (let j in newValue[i]) {
              //统计已整改数量
              if ((j === 'CHECKSTATE' || j === 'RECTIFYSTATE') && newValue[i][j].val === '已整改'&&newValue[i]['TYPE']=='隐患') {
                rectifySum += 1
              }
              //拼接字符串
              let dataRow = {}
              dataRow.DataTarget = j
              dataRow.Value = newValue[i][j].val
              dataRow.OriginalValue = newValue[i][j].val
              dataRow.PK = j === 'GUID'
              dataRow.DataType = j.indexOf('IMAGE') > -1 ? 'Store.ecidiDoc' : 'String'
              rowData.push(dataRow)
            }
            data.rowData = rowData
            data.children = []
            dataList.push(data)
          }
          obj.data = dataList
          this.detailValue = JSON.stringify(obj)

          //计算整改闭合率
          let totalSum = this.dataMap['RECTIFYNUM'].value
          if (totalSum != 0) {
            closeRate = ((rectifySum / totalSum) * 100).toFixed()
          }
          break
        }
      }
      //将计算出来的整改闭合率和整改完成数量写入list,进行保存
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].Id === 'CLOSERATE') {
          this.list[i].value = closeRate + "%"
        }
        if (this.list[i].Id === 'RECTIFYCOMNUM') {
          this.list[i].value = rectifySum
        }
      }
    },
    /**
     * 整改通知单提交前的校验
     * param:{string}str 表单的业务对象名称
     * return {string} 返回校验后的弹窗提示
     */
    rectifyCheck (str) {
      //如果是质量检查单
      if (str === 'PMQUALITY_RECTIFY') {
        //仅校验第二个流程
        if (this.row.NODEID === 'UserTask_2') {
          var totalSum = this.dataMap['RECTIFYNUM'].value
          var rectifyNum = this.dataMap['RECTIFYCOMNUM'].value
          var num = totalSum - rectifyNum;
          if (num) {
            return '你还有' + num + '个问题未整改，请检查是否完成所有整改任务，如无误请确认提交'
          }

        }
      }
      if (str === 'PMHSE_RECTIFY') {
        //仅校验第二个流程
        if (this.row.NODEID === 'UserTask_3') {
          var totalSum = this.dataMap['RECTIFYNUM'].value
          var rectifyNum = this.dataMap['RECTIFYCOMNUM'].value
          var num = totalSum - rectifyNum;
          if (num) {
            return '你还有' + num + '个问题未整改，请检查是否完成所有整改任务，如无误请确认提交'
          }

        }
      }
      return ''
    }
  },
  computed: {
    user () {
      return this.$store.state.user;
    },
    row () {//页面中使用row来指代当前记录
      return this.$store.state.currentRow;
    },
    flowConfig () {
      let map = {};
      let config = JSON.parse(this.row.DATACONFIGS);
      if (config.flowConfig && config.flowConfig[this.row.NODEID]) {
        let arr = config.flowConfig[this.row.NODEID].items;
        arr.forEach(function (item) {
          map[item.Id] = item;
        });
      }
      return map;
    },
    dataMap () {
      let map = {};
      if (this.list) {
        this.list.forEach(function (item) {
          map[item.Id] = item;
        });
      }
      return map
    },
  },
  components: {
    Timeline,
    TimelineItem,
    TimelineTitle
  }
}
</script>

<style scoped>
.test {
  overflow-y: hidden;
}
</style>

<style scoped>
.file_upload{
  margin-left: 26px;
}
.test /deep/  .my-cell-title span{
   position: relative;
   left:25px;
}
.test .picture-upload {
  padding: 10px 41px 0 41px !important;
}
.black {
  font-size:15px;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(38,42,52,1);
  line-height:21px;
  word-break: break-all;
}
.approveBtn {
  position: fixed;
  bottom: 0;
  width: 100%;
  box-sizing: border-box;
  min-height: 2.4rem;
  font-size: 0.8rem;
}
.btn-area {
  position: absolute;
  width: 100%;
  margin-top: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.btn-area-entrust{
  position: absolute;
  width: 100%;
  margin-top: 20px;
}
.btn {
  float: left;
  font-size: 14px;
  height: 45px;
  line-height: 45px;
  width: 139px;
  text-align: center;
  margin: 8px;
}
/* .approve-btn-area {
  margin-left: 33px !important;
} */
.general-btn {
    font-size: 16px;
    color: #ffffff;
    background-color: #4D86FF;
    border-radius: 2px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
}
.back-btn {
    font-size: 14px;
    color: #4D86FF;
    background-color: #ffffff;
    border: 1px solid #4D86FF;
    border-radius: 2px;
}
.entrust-btn {
  text-align: center;
  font-size:16px;
  font-family:PingFangSC-Medium,PingFang SC;
  font-weight:500;
  color: #ffffff;
  background-color: #4D86FF;
  border-radius: 2px;
  height: 45px;
  line-height: 45px;
  margin: 0 41px;
}
.approve-title{
  font-size:14px;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(75,75,75,1);
  line-height:20px;
}
.label-before {
  width: 4px;
  height: 11px;
  background: #4a8dff;
  margin-right: 7px;
  display: inline-block;
  /* margin-left: -14px; */
}
.progress-wait {
  color: #5AC8FA !important;
  background:#CDEEFD;
}
.progress-submit {
  color: #FF9500 !important;
  background:#FFEFB2;
}
.progress-agree {
  color: #4CD964 !important;
  background: #C9F3D0;
}
.progress-back {
  color: #FF3B30 !important;
  background:#FFC4C0;
}
.progress-finish {
  color: #D1D1D6 !important;
  background:#F1F1F2;
}
.detail-title {
  padding: 6px 0 6px 41px;
  font-size: 1rem;
}
.detail-table {
  font-size: 16px;
  color: #343434;
}
.attechment-item-name {
  font-size: 14px;
  color: #343434;
  margin-left: 16px;
}
.attechment-item-size {
  font-size: 12px;
}
.weui-cells {
  /*margin-top: 0 !important;*/
}
/* .handle {
  font-size: 13px;
} */
.content-container .timeline-circle {
  top: 14px !important;
}
.flow-box {
  margin-right: 0;
  padding-right: 18px;
  /* border-radius: 2px; */
  box-sizing: border-box;
  background: rgba(255,255,255,1);
  box-shadow: 0px 1px 9px 0px rgba(140,158,177,0.18);
  border-radius: 3px;
  border: 1px solid rgba(238,238,238,1);
}
.content-container {
  height: calc(100% - 56px);
  padding-top: 0;
  margin-top: 10px;
}
.weui-cells,
.vux-no-group-title {
  margin-top: 0 !important;
}
.vux-popup-dialog{
    position: unset !important;
}
.flow-box-taskComment{
  width: 92%;
  height: 70px;
  background: rgba(245,246,250,1);
  border-radius: 3px;
  opacity: 0.7;
  font-size: 14px;
  font-family: PingFangSC-Regular,PingFang SC;
  font-weight: 400;
  color: rgba(75,75,75,1);
  line-height: 20px;
  padding: 10px;   
  word-break: break-all;
  overflow-y: auto;
  margin-top: 10px;
}
.approve-textarea-entrust /deep/ .weui-textarea{
  background: #EEEEEE;
  opacity: 0.5;
  padding: 0 10px;
}
.new-name /deep/ .my-cell{
  width: 93%;
}
</style>

